﻿create PROCEDURE Sync.SP_Roles_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @Roles_Temp TABLE 
		(
			RoleID UniqueIdentifier,
			[RoleName] nvarchar(50),
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @Roles_Temp 
	   SELECT	Tbl.Col.value('RoleID[1]','uniqueidentifier') RoleID,
                Tbl.Col.value('RoleName[1]', 'nvarchar(50)') [RoleName],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/Roles') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[Roles] ([RoleID],[RoleName])
	SELECT t.[RoleID],t.[RoleName]
	FROM  @Roles_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.Roles_Tracking s
        WHERE t.RoleID = s.RoleID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[Roles]
	SET [Roles].[RoleName] = t.[RoleName] 
	FROM [dbo].[Roles] s JOIN @Roles_Temp t 
    ON t.RoleID = s.RoleID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.Roles_Tracking r
				  WHERE t.RoleID = r.RoleID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[Roles]
    FROM @Roles_Temp t JOIN [dbo].[Roles] s
    ON t.RoleID = s.RoleID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














